/*
 * ClientConnection.cpp
 *
 *  Created on: 13-01-2011
 *      Author: Michal Lisicki
 */

#include "ClientConnection.h"

using namespace Network;

ClientConnection::ClientConnection() {

}

ClientConnection::~ClientConnection() {

}

bool ClientConnection::init(std::string from, int port, unsigned char uid) {
	nextMsgNo_ = 0; clientIP_ = from; port_ = port; uid_ = uid;
#ifdef _WIN32
    WSADATA WsaData;
    WSAStartup(MAKEWORD(2,2), &WsaData);
#endif
	sock_ = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock_ == -1)
		return false;

	target_.sin_family = AF_INET;
	target_.sin_addr.s_addr = inet_addr((char*)from.c_str());
	target_.sin_port = htons(port_);

	if(bind(sock_, (struct sockaddr *) &target_, sizeof target_) == -1)
		return false;

	return true;
}

void ClientConnection::run() {
	do {
		Packet packet;
		packet = receivePacket();

		// Piotrek: jezeli typ pakietu nalezy do zbioru komend, to wystarczy pchnac do deserializera:
		// TODO: Commands::Deserializer::deserialize( packet.msg );
		// uwaga - tutaj zakladam, ze nie wyciapiesz z msg wstawionego tam MsgType
		// jezeli to zrobisz, to trzeba w deserializerze przeniesc zmienna ze switcha
		// do argumentu wywolania, a nie pobierac ja ze strumienia.

		if(packet.length_>0 && packet.type_==SET_BEHAVIOUR) {
			std::cout << packet.msg_ << std::endl;
		}
	} while(true);
}

std::istringstream& ClientConnection::getInputString() {
	return sin_;
}

std::ostringstream& ClientConnection::getOutputStream() {
	return sout_;
}

unsigned char ClientConnection::getNextMsgNo() {
	return nextMsgNo_++;
}

int ClientConnection::getPort() {
	return port_;
}

std::string ClientConnection::getClientIP() {
	return clientIP_;
}

unsigned char ClientConnection::getClientUID() {
	return uid_;
}
